<template>
  <div id="app">
    <h2>{{ message }}</h2>
    <div><button @click="download">下载</button></div>
    <input type="file" @change="handle" id="file_input" />
    <hr style="margin-bottom: 20px;" />
    <div id="output"></div>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from "vue";
import * as XLSX from "xlsx/xlsx.mjs";
import { downloadPDF } from "./tool.js"

const message = ref("excel转pdf合成测试版");

//公共样式设置
// const commonStyle = '<style>tr:first-child td{ background-color: #BDD7EE;} td { border: 1px solid #000; padding: 8px; }</style>'
const commonStyle = '<style>td { border: 1px solid #000; padding: 8px; }</style>'
//添加基础信息，如公司logo，公司名称
const companyLogo = ref('https://static.wxb.com.cn/frontEnd/images/login-manager/header-logo.png')
const companyName = ref('心有灵犀科技股份有限公司')
const baseInfo = ref(`<img src="${companyLogo.value}" alt="logo" style="width: 115px;height: 32px;">
    <div style="display: flex;justify-content: center;"><div style="margin: 10px 0;font-weight: 700;font-size: 25px;">${companyName.value}</div></div>`)

//sheet名称数据集合    
const sheet_name_list = ref([]);
// const catalogueList = computed(() => {
//   let str = ''
//   sheet_name_list.value.forEach((item, index) => {
//     str += `<div style="display: flex;justify-content: left;"><a href="#md${index}" style="margin: 10px 0;font-size: 20px;custor: pointer;">${item}</a></div>`
//   })
//   return str 
// })
//处理excel文件
const handleFile = (e) => {
  const files = e.target.files,
    f = files[0];
  const reader = new FileReader();
  reader.onload = function (e) {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    sheet_name_list.value = workbook.SheetNames;
    console.log("sheet_name_list", sheet_name_list);
    let allHtml = "";

    for (let i = 0; i < sheet_name_list.value.length; i++) {
      const html_str = XLSX.utils.sheet_to_html(
        workbook.Sheets[sheet_name_list.value[i]]
      );

      const sheet_tit = `<div id='md${i}' style="display: flex;justify-content: left;"><div style="margin: 10px 0;font-size: 20px;">${sheet_name_list.value[i]}</div></div>` 
      const styledHtml = sheet_tit + html_str
        .replace(
          "<table>",
          '<table style="border-collapse: collapse; width: 100%;margin: 20px 0">'
        )
        .replace("<body>", `<body>${commonStyle}`)
        .replace(/\><\/td>/g, 'style="border: none" ></td>');

          
      allHtml += styledHtml;
    }

    // allHtml = baseInfo.value + catalogueList.value + allHtml;
    allHtml = baseInfo.value + allHtml;
    console.log(allHtml);
    document.getElementById("output").innerHTML = `${allHtml}`;
  };
  reader.readAsArrayBuffer(f);
};

const pdfName = ref("test");
const download = () => {
  downloadPDF(document.querySelector("#output"), pdfName.value);
}
onMounted(() => {
  document
    .getElementById("file_input")
    .addEventListener("change", handleFile, false);
});
</script>
